package com.totoro.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.totoro.pojo.MyCoupon;
import com.totoro.pojo.ShopCoupon;
import com.totoro.pojo.User;
import com.totoro.service.ShopCouponService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TOTORO
 * @date 2021/7/15 11:18
 */
@Controller
@RequestMapping("/shopCoupon_logic")
public class ShopCouponController {

    @Autowired
    ShopCouponService shopCouponService;


    /**
     * 获得某个店铺的优惠券，最大优惠
     * @param shopId
     * @param allPrice
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping("/useShopCoupon")
    @ResponseBody
    public String getCartShopUseCoupon(@RequestParam("shopId") int shopId, @RequestParam("allPrice") double allPrice, HttpSession session){
        User user = (User) session.getAttribute("user");
        List<ShopCoupon> shopCoupons = shopCouponService.findAllCouponByUidAndSid(user.getUserId(), shopId);
        if(shopCoupons.size() < 1){
            return "no";
        }
        List<Boolean> isMeets = new ArrayList<>();
        // 循环检查一遍金额是否满足优惠券条件
        for (int i = 0; i < shopCoupons.size(); i++) {
            if(allPrice >= shopCoupons.get(i).getCouponUseMoney()){
                isMeets.add(true);
            }
        }
        if(!isMeets.contains(true)){
            return "no";
        }
        ShopCoupon maxCoupon = getMaxCoupon(shopCoupons, allPrice);
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(maxCoupon);
    }

    public String findShopAllCoupon(@RequestParam("shopId") int shopId, HttpSession session){
        User user = (User) session.getAttribute("user");
        List<ShopCoupon> shopCoupons = shopCouponService.findShopAllCouponBySid(shopId);
        List<ShopCoupon> myCouponList = shopCouponService.findShopCouponByUidAndSid(user.getUserId(), shopId);


        return "";
    }


    /**
     * 获取最大优惠的优惠券
     * @param list
     * @param allPrice
     * @return
     */
    public ShopCoupon getMaxCoupon(List<ShopCoupon> list, double allPrice){
        List<ShopCoupon> newScs = new ArrayList<>();
        for (ShopCoupon shopCoupon:list) {
            if(shopCoupon.getCouponUseMoney() <= allPrice){
                newScs.add(shopCoupon);
            }
        }
        return newScs.stream().sorted(Comparator.comparing(ShopCoupon::getCouponMoney).reversed()).collect(Collectors.toList()).get(0);
    }

}
